__author__ = 'aesop'
#coding:utf-8

import time
import get_mongo_con

class group():
    def __init__(self):
        self.owner = ""
        self.owner_permission = "3"
        self.others_permission = "1"
        self.group_name = ""
        self.group_member = []
        self.used_times = 0
        self.create_time = time.strftime("%Y-%m-%d %h")
        self.used_statics = []

    @staticmethod
    #如果是mysql的结果的话,用 a,b,c = 1,2,3 还比较实用，可惜用的mongodb啦
    def dic_to_obj(dic):
        the_group = group()
        the_group.owner = dic['owner']
        the_group.owner_permission = dic['owner_permission']
        the_group.others_permission = dic['other_permission']
        the_group.group_member = dic['group_member']
        the_group.group_name = dic['group_name']
        the_group.used_times = dic['used_times']
        the_group.create_time = dic['create_time']
        the_group.used_statics = dic['used_statics']
        the_group._id = dic['_id']
        return the_group

def check_group_unique(name):
    collection = get_mongo_con.get_collection("stu_group")
    result = collection.find_one({"group_name":name})
    if(result):
        return False
    else:
        return True


#检查加入新组时传的参数
def __check_arg(args):
    if((not 'owner' in args.keys()) or (args['owner'] < 0)):
        return False
    if(not check_group_unique(args['group_name'])):
        return False

    if((not 'group_member' in args.keys()) or len(args['group_member']) == 0):
        return False

    return True

def __init_args(args):
    if(not 'owner_permission' in args.keys()):
        args['owner_permission'] =  "3"
    if(not 'others_permission' in args.keys()):
        args['others_permission'] =  "1"
    args['used_time'] = 0
    args['create_time'] = time.strftime("%Y-%m-%d %H:%M:%S")
    args['used_statics'] = []
    return args

#新建分组
def new_group(args):
    if(not __check_arg(args)):
        return False
    else:
        collection = get_mongo_con.get_collection("stu_group")
        initialed_args = __init_args(args)
        return collection.insert(initialed_args)

#修改分组人员
def update_group_member(group_id,group_member):
    if(len(group_member)):
         collection = get_mongo_con.get_collection("stu_group")
         return collection.update({"_id":group_id},{"group_member": group_member})
    else:
        return False


def get_group_list(stu_id):
    collection = get_mongo_con.get_collection("stu_group")
    others_part =  [item for item in collection.find({"$and":[{"others_permission":"1"},{"owner":{"$ne":stu_id}}]})]
    self_part = [item for item in collection.find({"owner":stu_id})]
    return others_part + self_part







